package leetCode;

import java.util.HashSet;
import java.util.Set;

class Solution2 {
    //数组模拟hash表
    public int lengthOfLongestSubstring(String ss) {
        char[] s = ss.toCharArray();
        int[] hash = new int[128];//用数组模拟hash表
        int left = 0, right = 0, n = ss.length();
        int len = 0;
        while(right < n) {
            //进窗口
            hash[s[right]]++;
            //判断hash表
            while(hash[s[right]] > 1) {
                //删除left下标的元素,出窗口
                hash[s[left]]--;
                left++;
            }
            len = Math.max(len, right - left + 1);
            right++;
        }
        return len;
    }
    //自己尝试通过的代码
    public static int lengthOfLongestSubstring1(String s) {
        Set<Character> set = new HashSet<>();
        int len = 0, n = s.length();//长度
        for(int left = 0, right = 0; right < n; right++) {
            //入窗口
            if(!set.contains(s.charAt(right))) {
                set.add(s.charAt(right));
                len = Math.max(len, set.size());
            } else {
                while(s.charAt(left) != s.charAt(right)) {
                    set.remove(s.charAt(left));
                    left++;
                }
                set.remove(s.charAt(left));
                left++;
            }
        }
        return len;
    }
}